package cn.meye11.crm.controller;

import cn.meye11.crm.common.RestResponse;
import cn.meye11.crm.domain.query.ItemQuery;
import cn.meye11.crm.service.ItemService;
import cn.meye11.crm.domain.model.Item;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 项目表(Item)表服务控制类
 * 
 * @author makejava
 * @since 2023-11-18 19:20:43
 */
@Slf4j
@Controller
@RequestMapping("item")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ItemController {

    private final ItemService itemService;

    // 代码写到此区域
    @GetMapping("manage")
    public String manage(Model model, HttpSession session) {
        model.addAttribute("user", session.getAttribute("user"));
        return "item/item";
    }
    
    /************************************* 请在上方编写新代码 **************************************/
    // 此区域为自动生成的通用代码 尽量不直接修改

    @PostMapping("save")
    @ResponseBody
    public RestResponse<Long> save(@RequestBody Item model) {
        model.setCreatedBy("admin");//todo 根据登录用户获取
        Long id = itemService.save(model);
        return RestResponse.success("成功", id);
    }

    @DeleteMapping("remove/{id}")
    @ResponseBody
    public RestResponse<String> remove(@PathVariable Long id) {
        itemService.remove(id);
        return RestResponse.success("成功");
    }

    @PostMapping("update")
    @ResponseBody
    public RestResponse<String> update(@RequestBody Item model) {
        model.setModifiedBy("admin");//todo 根据登录用户获取
        if (model.getId() == null) {
            throw new RuntimeException("ID不能为空");
        }
        itemService.update(model);
        return RestResponse.success("成功");
    }

    @GetMapping("get/{id}")
    @ResponseBody
    public RestResponse<Item> get(Long id) {
        Item model = itemService.get(id);
        return model == null ? RestResponse.failed("不存在") : RestResponse.success("成功", model);
    }

    
    public RestResponse<Long> count(ItemQuery query) {
        Long count = itemService.count(query);
        return RestResponse.success("成功", count);
    }

    @GetMapping("list")
    @ResponseBody      
    public RestResponse<List<Item>> list(ItemQuery query) {
        return itemService.list(query);
    }

    @GetMapping("page")
    @ResponseBody
    public RestResponse<List<Item>> page(ItemQuery query) {
        return itemService.page(query);
    }
}
